package com.marketing.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.marketing.tenant.entity.Tenant;
import com.marketing.tenant.mapper.TenantMapper;
import com.marketing.tenant.service.TenantService;
import com.marketing.tenant.service.TenantConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 租户服务实现类
 * 使用MyBatis-Plus进行数据库操作
 */
@Service
public class TenantServiceImpl implements TenantService {

    private static final Logger log = LoggerFactory.getLogger(TenantServiceImpl.class);

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private TenantConfigService tenantConfigService;

    @Override
    public Tenant createTenant(Tenant tenant) {
        log.info("创建租户: {}", tenant.getTenantName());

        // 检查租户编码是否已存在
        if (existsByTenantCode(tenant.getTenantCode())) {
            throw new RuntimeException("租户编码已存在: " + tenant.getTenantCode());
        }

        // 检查邮箱是否已被使用
        if (existsByEmail(tenant.getContactEmail())) {
            throw new RuntimeException("邮箱已被使用: " + tenant.getContactEmail());
        }

        // 检查邮箱是否已被使用
        if (existsByEmail(tenant.getContactEmail())) {
            throw new RuntimeException("邮箱已被使用: " + tenant.getContactEmail());
        }

        // 设置默认值
        if (tenant.getStatus() == null) {
            tenant.setStatus(1);
        }
        if (tenant.getCreatedBy() == null) {
            tenant.setCreatedBy(1L); // 默认系统用户ID
        }
        if (tenant.getUpdatedBy() == null) {
            tenant.setUpdatedBy(1L); // 默认系统用户ID
        }

        // 设置时间戳
        LocalDateTime now = LocalDateTime.now();
        tenant.setCreateTime(now);
        tenant.setUpdateTime(now);

        // 保存租户
        int result = tenantMapper.insert(tenant);
        if (result <= 0) {
            throw new RuntimeException("租户创建失败");
        }

        // 初始化租户默认配置
        try {
            tenantConfigService.initDefaultConfigs(tenant.getId());
            log.info("租户默认配置初始化成功: 租户ID={}", tenant.getId());
        } catch (Exception e) {
            log.warn("租户默认配置初始化失败: 租户ID={}, 错误: {}", tenant.getId(), e.getMessage());
            // 不影响租户创建，只记录警告
        }

        log.info("租户创建成功: ID={}, 编码={}", tenant.getId(), tenant.getTenantCode());
        return tenant;
    }

    @Override
    public Tenant getTenantById(Long id) {
        log.debug("根据ID获取租户: {}", id);
        Tenant tenant = tenantMapper.selectOne(
            new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getId, id)
                .ne(Tenant::getStatus, 0) // 排除已删除的
        );
        if (tenant == null) {
            log.warn("租户不存在: ID={}", id);
        }
        return tenant;
    }

    @Override
    public Tenant getTenantByCode(String tenantCode) {
        log.debug("根据编码获取租户: {}", tenantCode);
        return tenantMapper.selectByTenantCode(tenantCode);
    }

    @Override
    public Tenant updateTenant(Tenant tenant) {
        log.info("更新租户: ID={}", tenant.getId());

        Tenant existingTenant = getTenantById(tenant.getId());
        if (existingTenant == null) {
            throw new RuntimeException("租户不存在: ID=" + tenant.getId());
        }

        // 检查租户编码是否与其他租户冲突
        if (!existingTenant.getTenantCode().equals(tenant.getTenantCode())) {
            if (tenantMapper.existsByTenantCodeExcludeId(tenant.getTenantCode(), tenant.getId()) > 0) {
                throw new RuntimeException("租户编码已存在: " + tenant.getTenantCode());
            }
        }

        // 检查邮箱是否与其他租户冲突
        if (!existingTenant.getContactEmail().equals(tenant.getContactEmail())) {
            if (tenantMapper.existsByEmailExcludeId(tenant.getContactEmail(), tenant.getId()) > 0) {
                throw new RuntimeException("邮箱已被使用: " + tenant.getContactEmail());
            }
        }

        // 保留创建时间和创建人
        tenant.setCreateTime(existingTenant.getCreateTime());
        tenant.setCreatedBy(existingTenant.getCreatedBy());
        tenant.setUpdateTime(LocalDateTime.now());
        
        if (tenant.getUpdatedBy() == null) {
            tenant.setUpdatedBy(1L); // 默认系统用户ID
        }

        // 更新租户
        int result = tenantMapper.updateById(tenant);
        if (result <= 0) {
            throw new RuntimeException("租户更新失败");
        }

        log.info("租户更新成功: ID={}, 编码={}", tenant.getId(), tenant.getTenantCode());
        return tenant;
    }

    @Override
    public boolean deleteTenant(Long id) {
        log.info("删除租户: ID={}", id);

        Tenant tenant = getTenantById(id);
        if (tenant == null) {
            log.warn("租户不存在: ID={}", id);
            return false;
        }

        // 不允许删除系统管理租户
        if ("SYSTEM".equals(tenant.getTenantCode())) {
            throw new RuntimeException("不允许删除系统管理租户");
        }

        // 逻辑删除：更新状态为0
        int result = tenantMapper.update(null,
            new LambdaUpdateWrapper<Tenant>()
                .eq(Tenant::getId, id)
                .set(Tenant::getStatus, 0)
                .set(Tenant::getUpdateTime, LocalDateTime.now())
                .set(Tenant::getUpdatedBy, 1L)
        );

        boolean success = result > 0;
        if (success) {
            log.info("租户删除成功: ID={}, 编码={}", id, tenant.getTenantCode());
        }
        return success;
    }

    @Override
    public List<Tenant> getAllTenants() {
        log.debug("获取所有租户列表");
        return tenantMapper.selectList(
            new LambdaQueryWrapper<Tenant>()
                .ne(Tenant::getStatus, 0) // 排除已删除的
                .orderByDesc(Tenant::getCreateTime)
        );
    }

    @Override
    public List<Tenant> getTenantsByStatus(Integer status) {
        log.debug("根据状态获取租户列表: status={}", status);
        return tenantMapper.selectList(
            new LambdaQueryWrapper<Tenant>()
                .eq(Tenant::getStatus, status)
                .orderByDesc(Tenant::getCreateTime)
        );
    }

    @Override
    public boolean activateTenant(Long id) {
        log.info("激活租户: ID={}", id);

        Tenant tenant = getTenantById(id);
        if (tenant == null) {
            log.warn("租户不存在: ID={}", id);
            return false;
        }

        int result = tenantMapper.update(null,
            new LambdaUpdateWrapper<Tenant>()
                .eq(Tenant::getId, id)
                .set(Tenant::getStatus, 1)
                .set(Tenant::getUpdateTime, LocalDateTime.now())
                .set(Tenant::getUpdatedBy, 1L)
        );

        boolean success = result > 0;
        if (success) {
            log.info("租户激活成功: ID={}, 编码={}", id, tenant.getTenantCode());
        }
        return success;
    }

    @Override
    public boolean suspendTenant(Long id) {
        log.info("暂停租户: ID={}", id);

        Tenant tenant = getTenantById(id);
        if (tenant == null) {
            log.warn("租户不存在: ID={}", id);
            return false;
        }

        // 不允许暂停系统管理租户
        if ("SYSTEM".equals(tenant.getTenantCode())) {
            throw new RuntimeException("不允许暂停系统管理租户");
        }

        int result = tenantMapper.update(null,
            new LambdaUpdateWrapper<Tenant>()
                .eq(Tenant::getId, id)
                .set(Tenant::getStatus, 3)
                .set(Tenant::getUpdateTime, LocalDateTime.now())
                .set(Tenant::getUpdatedBy, 1L)
        );

        boolean success = result > 0;
        if (success) {
            log.info("租户暂停成功: ID={}, 编码={}", id, tenant.getTenantCode());
        }
        return success;
    }

    @Override
    public boolean existsByTenantCode(String tenantCode) {
        return tenantMapper.existsByTenantCode(tenantCode) > 0;
    }

    @Override
    public boolean existsByEmail(String email) {
        return tenantMapper.existsByEmail(email) > 0;
    }
}